package com.notary.aspect;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.notary.constants.Constant;
import com.notary.util.DesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.*;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据解密切面
 */


@Component
@ControllerAdvice(basePackages = "com.notary.controller")
@Slf4j
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {

    @Value("${office.deskey}")
    private String deskey;
    @Value("${office.desIv}")
    private String desIv;

    @Value("${request.encryption}")
    private int encryption;


    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        Method method = methodParameter.getMethod();
        String name = method.getDeclaringClass().getName();
        List<String> className = new ArrayList<>();
        className.add("ReceiveDataController");
        if (CollectionUtil.isNotEmpty(className)) {
            for (String str : className) {
                if (name.indexOf(str) > 0) {
                    return false;
                }
            }

        }
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage request, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        if (encryption != Constant.requestEncryption.YES.getValue()) {
            return request;
        }
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            //这个request其实就是入参 可以从这里获取流
            //入参放在HttpInputMessage里面  这个方法的返回值也是HttpInputMessage
            InputStream inputStream = request.getBody();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
        //获取请求数据

        String string = stringBuilder.toString();
        JSONObject jsonObject = JSON.parseObject(string);
        string = jsonObject.getString("data");
        /*****************进行解密start*******************/
        log.info("【接受的请求数据】string:{}", string);
        String decode = null;
        try {
            decode = DesUtil.decode(deskey, desIv, string);
            log.info("【解密后的请求数据】decode:{}", decode);
        } catch (Exception e) {
            log.error("解密数据出错,{}", e.getMessage());
        }
        //把数据放到我们封装的对象中
        String finalDecode = decode;
        return new HttpInputMessage() {
            @Override
            public HttpHeaders getHeaders() {
                return request.getHeaders();
            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(finalDecode.getBytes("UTF-8"));
            }
        };
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }


}


